package bar.dark.lee.budget;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout.LayoutParams;
import bar.dark.lee.BDConstents;
import bar.dark.lee.R;
import bar.dark.lee.SuperActivity;
import bar.dark.lee.common.BDUtil;
import bar.dark.lee.common.DBSQLite;
import bar.dark.lee.common.DBSQLite.ParseSelectData;
import bar.dark.lee.fan.FanAdapter;
import bar.dark.lee.fan.FanOutActivity;
import bar.dark.lee.setting.TipInfoActivity;
import bar.dark.lee.setting.TipsActivity;
import bar.dark.lee.setting.category.CategoryData;
import bar.dark.lee.stats.StatsCategoryData;

public class BudgetListActivity extends SuperActivity
{
	public static String BUDGET_ID = "BUDGET_ID";
	
	private DBSQLite sql;
	
	private ListView listView;
	
	private int year;
	private int month;
	private int date;
	
	private int tempYear;
	private int tempMonth;
	private int tempDate;
	
	private ArrayList<StatsCategoryData> outList;
	private ArrayList<BudgetData> totalList;
	
	private View resultView;
	
	private int startDate;
	
	private View leftDateButton;
	private View rightDateButton;
	private TextView dateTextView;
	
	private String toDate = "";
	
	private int flag;
	
	private String tableName;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		sql = DBSQLite.getInstance(superContext);
		
		setContentView(R.layout.budget_list_activity);
		
		Calendar cal = Calendar.getInstance();
		
		Intent intent = getIntent();
		flag = intent.getIntExtra(BudgetTabActivity.BUDGET_FLAG, 0);
		year = intent.getIntExtra(BudgetActivity.BUDGET_YEAR, cal.get(Calendar.YEAR));
		month = intent.getIntExtra(BudgetActivity.BUDGET_MONTH, cal.get(Calendar.MONTH));
		date = intent.getIntExtra(BudgetActivity.BUDGET_DATE, cal.get(Calendar.DAY_OF_MONTH));
		
		if (flag == BudgetTabActivity.OUT_FLAG)
		{
			setTitle("지출 예산 목록");
			tableName = "budget_category";
		}
		else if (flag == BudgetTabActivity.IN_FLAG)
		{
			setTitle("수입 예산 목록");
			tableName = "budget_in_category";
		}
		else if (flag == BudgetTabActivity.MOVE_FLAG)
		{
			setTitle("이동 예산 목록");
			tableName = "budget_move_category";
		}
		
		
		setFindView();
		setOnClickListener();
	}
	
	@Override
	protected void onResume()
	{
		super.onResume();
		
		new ShowDialog().execute(0);
	}
	
	private void setFindView()
	{
		listView = (ListView) findViewById(R.id.budgetListView);
		
		resultView = getLayoutInflater().inflate(R.layout.view_no_result, null);
		
		leftDateButton = findViewById(R.id.budgetListDateLeftButton);
		rightDateButton = findViewById(R.id.budgetListDateRightButton);
		dateTextView = (TextView) findViewById(R.id.budgetListDateText);
		
		// 달 시작일 가져온다
    	SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
    	startDate = Integer.parseInt(pref.getString(BDConstents.START_DATE, "1"));
    	
    	if (month < 9)
		{
			toDate = year + "0" + (month+1);
		}
		else
		{
			toDate = year + "" + (month+1);
		}
	}
	
	private void setOnClickListener()
	{
		leftDateButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				startLeftMonthButton();
			}
		});
		
		rightDateButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				startRightMonthButton();
			}
		});
	}

	private void setData()
	{
		String firstDate = "";
    	String lastDate = "";
		
		if (startDate == 1) 
		{
			firstDate = BDUtil.getDateDB(year, month+1, 00);
			lastDate = BDUtil.getDateDB(year, month+1, 32);
		}
		else
		{
			if (month+1 == 1)
			{
				firstDate = BDUtil.getDateDB(year, 1, startDate);
				lastDate = BDUtil.getDateDB(year, 2, startDate-1);
			}
			else if (month+1 == 12)
			{
				firstDate = BDUtil.getDateDB(year, 12, startDate);
				lastDate = BDUtil.getDateDB(year+1, 1, startDate-1);
			}
			else
			{
				firstDate = BDUtil.getDateDB(year, month+1, startDate);
				lastDate = BDUtil.getDateDB(year, month+2, startDate-1);
				
			}
		}
		
		totalList = new ArrayList<BudgetData>();
		
		sql.selectMapTile(superContext, "SELECT * FROM " + tableName + " WHERE count = " 
				+ toDate + ";", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int idIdx = c.getColumnIndex("id");
				int nameIdx = c.getColumnIndex("name");
				int moneyIdx = c.getColumnIndex("money");
				int countIdx = c.getColumnIndex("count");
				int linkidIdx = c.getColumnIndex("linkid");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					BudgetData data = new BudgetData();
					
					data.setId(c.getInt(idIdx) + "");
					data.setName(c.getString(nameIdx));
					data.setMoney(c.getString(moneyIdx));
					data.setCount(c.getString(countIdx));
					data.setLinkid(c.getString(linkidIdx));
					
					totalList.add(data);
					c.moveToNext();
				}
			}
		});
		
		outList = new ArrayList<StatsCategoryData>();
		
		for (int i = 0; i < totalList.size(); i++)
		{
			String category = totalList.get(i).getName();
			
			if (flag == BudgetTabActivity.OUT_FLAG)
			{
				String categoryQuery = "SELECT category, SUM(outmoney" + 
						") omoney, SUM(postmoney) pmoney FROM in_out WHERE " +
						"category = '" + BDUtil.getApostrophe(category) + "' and " +
						"inmoney in ('0') and date >= " +
						firstDate + " and date <= " +
						lastDate + " and type not in (" + 
						BDConstents.INOUT_TYPE + ", " +
						BDConstents.OUTIN_TYPE + ", " +
						BDConstents.MYBANK_INOUT_TYPE + ") " +
						"GROUP BY category "
						+ "UNION ALL "
						+ "SELECT category, SUM(outmoney" + 
						") omoney, SUM(postmoney) pmoney FROM in_out WHERE " +
						"category = '" + BDUtil.getApostrophe(category) + "' and " +
						"date >= " +
						firstDate + " and date <= " +
						lastDate + " and category in ('" 
						+ BDConstents.CATEGORY_SUSUMONEY + "') GROUP BY category;";
				
				sql.selectMapTile(this, categoryQuery, new ParseSelectData()
				{
					@Override
					public void resultData(Cursor c)
					{
						int categoryIdx = c.getColumnIndex("category");
						int moneyIdx = c.getColumnIndex("omoney");
						int pmoneyIdx = c.getColumnIndex("pmoney");
						
						BigDecimal money = BigDecimal.ZERO;
						BigDecimal pmoney = BigDecimal.ZERO;
						String name = "";
						
						c.moveToFirst();
						
						for (int i = 0; i < c.getCount(); i++)
						{
							StatsCategoryData data = new StatsCategoryData();
							name = c.getString(categoryIdx);
							money = new BigDecimal(c.getString(moneyIdx));
							pmoney = new BigDecimal(c.getString(pmoneyIdx));
							data.setCategory(name);
							data.setMoney(money.add(pmoney).toString());
							outList.add(data);
							
							c.moveToNext();
						}
					}
				});
			}
			else if (flag == BudgetTabActivity.IN_FLAG)
			{
				String categoryQuery = "SELECT category, SUM(inmoney) imoney FROM in_out WHERE " +
						"category = '" + BDUtil.getApostrophe(category) + "' and " +
						"inmoney not in ('0') and date >= " +
						firstDate + " and date <= " +
						lastDate + " and type not in (" + 
						BDConstents.INOUT_TYPE + ", " +
						BDConstents.OUTIN_TYPE + ", " +
						BDConstents.MYBANK_INOUT_TYPE + ") " +
						"and category not in ('" + 
						BDConstents.CATEGORY_POST_OUT +
						"') GROUP BY category;";
				
				sql.selectMapTile(this, categoryQuery, new ParseSelectData()
				{
					@Override
					public void resultData(Cursor c)
					{
						int categoryIdx = c.getColumnIndex("category");
						int moneyIdx = c.getColumnIndex("imoney");
						
						BigDecimal money = BigDecimal.ZERO;
						String name = "";
											
						c.moveToFirst();
						
						for (int i = 0; i < c.getCount(); i++)
						{
							StatsCategoryData data = new StatsCategoryData();
							name = c.getString(categoryIdx);
							money = new BigDecimal(c.getString(moneyIdx));
							data.setCategory(name);
							data.setMoney(money.toString());
							outList.add(data);
							
							c.moveToNext();
						}
					}
				});
			}
			else if (flag == BudgetTabActivity.MOVE_FLAG)
			{
				String inOutQuery = "SELECT category, SUM(outmoney) omoney, SUM(postmoney) pmoney " +
						"FROM in_out WHERE date >= " +
						firstDate + " and date <= " +
						lastDate + " and " +
						"category = '" + BDUtil.getApostrophe(category) + "' and " +
						"type = " + BDConstents.INOUT_TYPE + 
						" GROUP BY category;";
				
				sql.selectMapTile(this, inOutQuery, new ParseSelectData()
				{
					@Override
					public void resultData(Cursor c)
					{
						int categoryIdx = c.getColumnIndex("category");
						int omoneyIdx = c.getColumnIndex("omoney");
						int pmoneyIdx = c.getColumnIndex("pmoney");
						
						BigDecimal omoney = BigDecimal.ZERO;
						String name = "";
											
						c.moveToFirst();
						
						for (int i = 0; i < c.getCount(); i++)
						{
							StatsCategoryData data = new StatsCategoryData();
							name = c.getString(categoryIdx);
							omoney = new BigDecimal(c.getString(omoneyIdx));
							omoney = omoney.add(new BigDecimal(c.getString(pmoneyIdx)));
							data.setCategory(name);
							
							data.setMoney(omoney.toString());
							outList.add(data);
							
							c.moveToNext();
						}
					}
				});
				
				inOutQuery = "SELECT category, SUM(inmoney) imoney " +
						"FROM in_out WHERE date >= " +
						firstDate + " and date <= " +
						lastDate + " and " +
						"category = '" + BDUtil.getApostrophe(category) + "' and " +
						"type = " +	BDConstents.OUTIN_TYPE + 
						" GROUP BY category;";
				
				sql.selectMapTile(this, inOutQuery, new ParseSelectData()
				{
					@Override
					public void resultData(Cursor c)
					{
						int categoryIdx = c.getColumnIndex("category");
						int imoneyIdx = c.getColumnIndex("imoney");
						
						BigDecimal imoney = BigDecimal.ZERO;
						String name = "";
											
						
						c.moveToFirst();
						
						for (int i = 0; i < c.getCount(); i++)
						{
							StatsCategoryData data = new StatsCategoryData();
							name = c.getString(categoryIdx);
							imoney = new BigDecimal(c.getString(imoneyIdx));
							data.setCategory(name);
							
							data.setMoney(imoney.toString());
							
							boolean flag = false;
							
							for (int j = 0; j < outList.size(); j++)
							{
								if (data.getCategory().equals(outList.get(j).getCategory()))
								{
									BigDecimal tempMoney = new BigDecimal(outList.get(j).getMoney());
									
									outList.get(j).setMoney(tempMoney.add(new BigDecimal(data.getMoney())).toString());
									
									flag = true;
								}
							}
							
							if (flag == false)
							{
								outList.add(data);
							}
							
							c.moveToNext();
						}
					}
				});
				
				inOutQuery = "SELECT type, category, SUM(outmoney) omoney, " +
						"SUM(inmoney) imoney, SUM(postmoney) pmoney " +
						"FROM in_out WHERE date >= " +
						firstDate + " and date <= " +
						lastDate + " and " +
						"category = '" + BDUtil.getApostrophe(category) + "' and " +
						"type = " +	BDConstents.MYBANK_INOUT_TYPE + 
						" GROUP BY category;";
				
				sql.selectMapTile(this, inOutQuery, new ParseSelectData()
				{
					@Override
					public void resultData(Cursor c)
					{
						int categoryIdx = c.getColumnIndex("category");
						int omoneyIdx = c.getColumnIndex("omoney");
						int pmoneyIdx = c.getColumnIndex("pmoney");
						int imoneyIdx = c.getColumnIndex("imoney");
						
						BigDecimal omoney = BigDecimal.ZERO;
						BigDecimal pmoney = BigDecimal.ZERO;
						BigDecimal imoney = BigDecimal.ZERO;
						String name = "";
											
						c.moveToFirst();
						
						for (int i = 0; i < c.getCount(); i++)
						{
							StatsCategoryData data = new StatsCategoryData();
							name = c.getString(categoryIdx);
							omoney = new BigDecimal(c.getString(omoneyIdx));
							pmoney = new BigDecimal(c.getString(pmoneyIdx));
							imoney = new BigDecimal(c.getString(imoneyIdx));
							data.setCategory(name);
							
							omoney = omoney.add(pmoney);
							
							data.setMoney(omoney.toString());
							
							boolean flag = false;
							
							for (int j = 0; j < outList.size(); j++)
							{
								if (data.getCategory().equals(outList.get(j).getCategory()))
								{
									BigDecimal tempMoney = new BigDecimal(outList.get(j).getMoney());
									
									outList.get(j).setMoney(tempMoney.add(new BigDecimal(data.getMoney())).toString());
									
									flag = true;
								}
							}
							
							if (flag == false)
							{
								outList.add(data);
							}
							
							c.moveToNext();
						}
					}
				});
			}
		}
	}
	
	private OnItemClickListener onItemClickListener = new OnItemClickListener()
	{
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
				long arg3)
		{
			BudgetData data = (BudgetData) arg0.getAdapter().getItem(pos);
			
			Intent intent = new Intent(superContext, BudgetUpdateActivity.class);
			intent.putExtra(BudgetTabActivity.BUDGET_FLAG, flag);
			intent.putExtra(BUDGET_ID, data.getId());
			startActivity(intent);
		}
	};
	
	private void startLeftMonthButton()
	{
		if (month == 0)
		{
			year--;
			month = 11;
		}
		else
		{
			month--;
		}
		
		BDUtil.startLeftDegrees(dateTextView).setAnimationListener(new AnimationListener()
		{
			@Override
			public void onAnimationStart(Animation animation)
			{
			}
			
			@Override
			public void onAnimationRepeat(Animation animation)
			{
			}
			
			@Override
			public void onAnimationEnd(Animation animation)
			{
				if (month < 9)
				{
					toDate = year + "0" + (month+1);
				}
				else
				{
					toDate = year + "" + (month+1);
				}
				
				new ShowDialog().execute(0);
			}
		});
	}	
	
	private void startRightMonthButton()
	{
		if (month == 11)
		{
			year++;
			month = 0;
		}
		else
		{
			month++;
		}
		
		BDUtil.startRightDegrees(dateTextView).setAnimationListener(new AnimationListener()
		{
			@Override
			public void onAnimationStart(Animation animation)
			{
			}
			
			@Override
			public void onAnimationRepeat(Animation animation)
			{
			}
			
			@Override
			public void onAnimationEnd(Animation animation)
			{
				if (month < 9)
				{
					toDate = year + "0" + (month+1);
				}
				else
				{
					toDate = year + "" + (month+1);
				}
				
				new ShowDialog().execute(0);
			}
		});
	}
	
	private class BudgetAdapter extends ArrayAdapter<BudgetData>
	{
		private ArrayList<BudgetData> list;
		private ArrayList<StatsCategoryData> cateList;
		
		public BudgetAdapter(Context context, int textViewResourceId,
				List<BudgetData> objects, ArrayList<StatsCategoryData> list)
		{
			super(context, textViewResourceId, objects);
			this.list = (ArrayList<BudgetData>) objects;
			this.cateList = list;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			View v = convertView;
			
			if (v == null)
			{
				v = getLayoutInflater().inflate(R.layout.list_item_budget, null);
			}
			
			BudgetData bData = list.get(position);
			
			BigDecimal outMoney = BigDecimal.ZERO;
			
			for (int i = 0; i < cateList.size(); i++)
			{
				String name = cateList.get(i).getCategory();
				
				if (name.equals(bData.getName()))
				{
					outMoney = new BigDecimal(cateList.get(i).getMoney());
				}
			}
			
			TextView flagText = (TextView) v.findViewById(R.id.listItemBudgetFlagTextView);
			TextView tv1 = (TextView) v.findViewById(R.id.listItemBudgetCategory);
			TextView tv2 = (TextView) v.findViewById(R.id.listItemBudgetTotalMoney);
			TextView tv3 = (TextView) v.findViewById(R.id.listItemBudgetOutMoney);
			TextView tv4 = (TextView) v.findViewById(R.id.listItemBudgetMoney);
			View dangerView = v.findViewById(R.id.listItemBudgetDangerView);
			TextView dangerTextView = (TextView) v.findViewById(R.id.listItemBudgetDangerTextView);
			
			if (flag == BudgetTabActivity.OUT_FLAG)
			{
				flagText.setText("지출금액");
			}
			else if (flag == BudgetTabActivity.IN_FLAG)
			{
				flagText.setText("수입금액");
			}
			else if (flag == BudgetTabActivity.MOVE_FLAG)
			{
				flagText.setText("이동금액");
			}
			
			tv1.setText(bData.getName());
			tv2.setText(BDUtil.getWon(bData.getMoney()) + shape);
			tv3.setText(BDUtil.getWon(outMoney.toString()) + shape);
			
			BigDecimal money = BigDecimal.ZERO;
			
			money = new BigDecimal(bData.getMoney()).subtract(outMoney);
			
			tv4.setText(BDUtil.getWon(money.toString()) + shape);
			
//			if (money.compareTo(BigDecimal.ZERO) > 0)
//			{
//				tv4.setText(money.toString() + shape);
//			}
//			else
//			{
//				tv4.setText("0" + shape);
//			}
			
			BigDecimal totalMoney = new BigDecimal(bData.getMoney());
			
			int avgCount = 0;
			int percent = 0;
			
			avgCount = (int)(((double)Math.abs(outMoney.doubleValue()) 
					/ (double)(totalMoney.doubleValue())) * 100);
			
			percent = avgCount;
			
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LayoutParams.FILL_PARENT);
			
			if ((int)percent > 100)
			{
				params.weight = 100;
			}
			else
			{
				params.weight = percent;
			}
			
			dangerView.setLayoutParams(params);
			dangerTextView.setText(((int)percent) + "%");
			
			return v;
		}
	}
	
	/**
	 * 다이얼로그 뛰우기 
	 */
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>{
		ProgressDialog dialog = null;
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog = new ProgressDialog(superContext);
			dialog.setCancelable(false);
			dialog.setMessage("Loading...");
			dialog.show();
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) {
			
			if (arg0[0] == 0)
			{
				setData();
				
				return 0;
			}
			
			return null;
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			
			dialog.dismiss();
			
			if (result == 0)
			{
				if (listView.getFooterViewsCount() > 0)
				{
					listView.removeFooterView(resultView);
				}
				
				if (totalList.size() < 1)
				{
					listView.addFooterView(resultView);
					listView.setFooterDividersEnabled(false);
					listView.setOnItemClickListener(null);
				}
				else
				{
					listView.setSelected(true);
					listView.setOnItemClickListener(onItemClickListener);
					listView.setFooterDividersEnabled(true);
				}
				
				BudgetAdapter adapter = new BudgetAdapter(superContext, 
						R.layout.list_item_budget, totalList, outList);
				listView.setAdapter(adapter);
				adapter.notifyDataSetChanged();
				
				// 시작일에 따라서 날짜 셋팅
				if (startDate == 1)
				{
		    		dateTextView.setText(year + "년 " + (month+1) + "월");
				}
		    	else if (date < startDate)
				{
		    		tempYear = year;
		    		tempMonth = month;
		    		tempDate = date;
		    		
		    		if (month == 11)
		    		{
		    			tempYear++;
		    			tempMonth = 0;
		    		}
		    		else
		    		{
		    			tempMonth++;
		    		}
		    		
					dateTextView.setText(year + "년 " + (month+1) + "월 ~ " 
									+ tempYear + "년 " + (tempMonth+1) + "월");
				}
				else
				{
					tempYear = year;
		    		tempMonth = month;
		    		tempDate = date;
		    		
		    		if (month == 11)
		    		{
		    			tempYear++;
		    			tempMonth = 0;
		    		}
		    		else
		    		{
		    			tempMonth++;
		    		}
					
		    		dateTextView.setText(year + "년 " + (month+1) + "월 ~ " 
							+ tempYear + "년 " + (tempMonth+1) + "월");
				}
			}
		}
	}

	@Override
	protected void tipButton()
	{
		Intent intent = new Intent(this, TipInfoActivity.class);
		intent.putExtra(TipsActivity.TIP_REQUEST_KEY, TipsActivity.TIP_BUDGET);
		startActivity(intent);
	}
}
